import requests
import time
from lxml import etree
from ddddocr import DdddOcr

ocr = DdddOcr(show_ad=False)
while True:
    img_res = requests.get(f'https://www.gushiwen.cn/RandCode.ashx?t={int(time.time() * 1000)}')
    print(img_res.cookies)
    with open('./static/yzm/古诗文.jpg', 'wb') as f:
        f.write(img_res.content)
    r = ocr.classification(img_res.content)
    print(r)

    login_get_res = requests.get('https://www.gushiwen.cn/user/login.aspx')
    # print(login_get_res.text)

    tree = etree.HTML(login_get_res.text)
    __VIEWSTATE = tree.xpath('//input[@id="__VIEWSTATE"]/@value')[0]
    __VIEWSTATEGENERATOR = tree.xpath('//input[@id="__VIEWSTATEGENERATOR"]/@value')[0]
    # print(__VIEWSTATE, __VIEWSTATEGENERATOR)

    login_post_res = requests.post('https://www.gushiwen.cn/user/login.aspx', data={
        '__VIEWSTATE': __VIEWSTATE,
        '__VIEWSTATEGENERATOR': __VIEWSTATEGENERATOR,
        'email': '15225989853',
        'pwd': '123456',
        'code': f'{r}',
        'denglu': '登录'
    }, cookies=img_res.cookies)
    if '提交失败，您输入的验证码有误！' in login_post_res.text:
        print('验证码识别错误')
    else:
        break

collect_res = requests.get('https://www.gushiwen.cn/user/collect.aspx', cookies=login_post_res.cookies)
# print(collect_res.text)
tree = etree.HTML(collect_res.text)
collect_list = tree.xpath('//div[@class="sons"]/div[@class="cont"]')
for item in collect_list:
    title = item.xpath('.//a/text()')[0]
    url = item.xpath('.//a/@href')[0]
    print(title,url)
